package load;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "UploadServlet", value = "/UploadServlet")
public class UploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("文件已经上传");
//        判断是否为多段数据
        if (ServletFileUpload.isMultipartContent(request)) {
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
//            创建用于解析上传数据的工具类
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            try {
                List<FileItem> list = servletFileUpload.parseRequest(request);
//                判断是否为普通类还是文件
                for (FileItem fileItem : list) {
//                    如果不是文件
                    if (fileItem.isFormField()) {
                        System.out.println("表单项的name为："+fileItem.getFieldName());
                        System.out.println("表单项的value为："+fileItem.getString("UTF-8"));
                    }else {//是文件
                        System.out.println("表单项的name为："+fileItem.getFieldName());
                        System.out.println("上传的文件名为："+fileItem.getName());
//                        上传文件的保存
                        fileItem.write(new File("D:\\Code\\Java\\JavaWebStudy1\\EL_JSTL\\src\\main\\resources\\imgs"));
                    }
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }


        }


    }
}
